package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FastDFSUtil;
import com.ruoyi.system.domain.SysOrganization;
import com.ruoyi.system.domain.SyseEventsPosted;
import com.ruoyi.system.domain.mongodb.Schools;
import com.ruoyi.system.domain.mongodb.Users;
import com.ruoyi.system.mapper.SysEventsPostedMapper;
import com.ruoyi.system.mapper.SysOrganizationMapper;
import com.ruoyi.system.mongo.Impl.StudentDaoImpl;
import com.ruoyi.system.service.ISysEventsPostedService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.SQLOutput;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 赛事发布 服务层处理
 *
 * @author ganshiyu
 */
@Service
public class SysEventsPostedServiceImpl implements ISysEventsPostedService {
     @Autowired
     private SysEventsPostedMapper competitionMapper;
     @Autowired
     private FastDFSUtil fastDFSUtil;
     @Autowired
     StudentDaoImpl studentDao;
     @Autowired
     MongoTemplate mongoTemplate;
     @Autowired
     private SysOrganizationMapper organizationMapper;

     /**
      * 查询活动结束时间
      * @param epid
      * @return
      */
     @Override
     public String queryEndTimeByEpid(String epid) {
          return competitionMapper.queryEndTimeByEpid(epid);
     }

     /**
      * 教师页面我的邀请查询被邀请的赛事信息
      * @param tid
      * @return
      */
     @Override
     public List<SyseEventsPosted> queryEventByTid(String tid) {
          List<SyseEventsPosted> syseEventsPostedList = competitionMapper.queryEventByTid(tid);
          for (SyseEventsPosted syseEventsPosted : syseEventsPostedList) {
               String epsigstart = syseEventsPosted.getEpsigstart();
               String epfinalend = syseEventsPosted.getEpfinalend();
               String starEnd=epsigstart+"----"+epfinalend;
               syseEventsPosted.setStarEnd(starEnd);
          }
          return syseEventsPostedList;
     }

     /**
      * 查询所有赛事信息
      * @return
      */
     @Override
     public List<SyseEventsPosted> querySyseEventsPostedByEplevel() {
          return competitionMapper.querySyseEventsPostedByEplevel();
     }

     /**
      * 教师页面查询所有区域级赛事信息
      * @return
      */
     @Override
     public List<SyseEventsPosted> queryAllSyseEventsPosted(SyseEventsPosted syseEventsPosted) {
          return competitionMapper.queryAllSyseEventsPosted(syseEventsPosted);
     }

     /**
      * 添加赛事发布
      *后台管理和校园管理平台共同使用
      * @param syseEventsPosted 实体类
      * @return 结果
      */
     @Override
     public int insertEventsPosted(SyseEventsPosted syseEventsPosted) {

          if (!StringUtils.isEmpty(syseEventsPosted.getEpsponsor())){
               //主办方id和名称分割
               String[] sponsor = syseEventsPosted.getEpsponsor().split(",");
               //主办方名称
               syseEventsPosted.setEpsponsor(sponsor[0]);
               //封装机构对象，做查询
               SysOrganization org = new SysOrganization();
               org.setOrganizationname(sponsor[0]); //机构名称
               org.setSchoolId(sponsor[1]); //学校ID
               //查询是否有该机构信息，如果没有则添加一个
               List<SysOrganization> orgList = organizationMapper.querySysOrganization(org);
               if (orgList == null || orgList.size() ==0) {
                   org.setCreate_by(syseEventsPosted.getEptid()); //操作人
                    organizationMapper.saveSysOrganization(org);
                    //主办方ID
                    syseEventsPosted.setEpsponsorid(org.getOrganizationid());
               } else {
                    //主办方ID
                    syseEventsPosted.setEpsponsorid(orgList.get(0).getOrganizationid());
               }
          }

          //省市区分割
          String eppros = syseEventsPosted.getEppro();
          String[] split = null;
          int i = 0;
          if (eppros.length() != 0) {
               split = eppros.split("/");
               //判断是否具备省市县
               if (split.length==1){
                    syseEventsPosted.setEppro(split[0]);
               }
               if (split.length == 2) {
                    syseEventsPosted.setEppro(split[0]);
                    syseEventsPosted.setEpcity(split[1]);
               } else if(split.length ==3){
                    syseEventsPosted.setEppro(split[0]);
                    syseEventsPosted.setEpcity(split[1]);
                    syseEventsPosted.setEparea(split[2]);
               }
          }

          String filepath = "";
          try {
               //获取文件对象
               MultipartFile file = syseEventsPosted.getFile();
               System.out.println(file.getOriginalFilename());
               if (file.getSize()!=0) {
                    //上传文件
                    filepath = fastDFSUtil.uploadFile(file);
                    System.out.println("file：" + filepath);
                    //获取文件全路径
                    String url = fastDFSUtil.getResAccessUrl(filepath);
                    System.out.println("url：" + url);
                    //封装对象
                    syseEventsPosted.setEppic(url);
               }
          } catch (IOException e) {
               e.printStackTrace();
          }
          //添加之前先查重
          long rechecking = competitionMapper.rechecking(syseEventsPosted);
          System.out.println(rechecking);
          //查不到时再添加
          if (rechecking==0){
               System.out.println("添加成功");
               if (StringUtils.isEmpty(syseEventsPosted.getEpstage())) {
                    syseEventsPosted.setProgressStatus("4"); //默认设置初赛阶段
               } else if (syseEventsPosted.getEpstage().indexOf("初赛")>-1) {
                    syseEventsPosted.setProgressStatus("4"); //默认设置初赛阶段
               } else if (syseEventsPosted.getEpstage().indexOf("复赛")>-1) {
                    syseEventsPosted.setProgressStatus("5"); //默认设置初赛阶段
               } else if (syseEventsPosted.getEpstage().indexOf("决赛")>-1) {
                    syseEventsPosted.setProgressStatus("6"); //默认设置初赛阶段
               }
               i = competitionMapper.insertEventsPosted(syseEventsPosted);
          }
          return i;
     }

     /**
      * 赛事管理  条件查询+分页
      * 后台管理和校园管理平台共同使用
      * @param syseEventsPosted 实体类
      * @return 对象列表
      */
     @Override
     public Map<String, Object> selectByPage(SyseEventsPosted syseEventsPosted) {
          Map<String, Object> data = new HashMap<>();

          /* 校园工作台时涉及以下方法  开始*/
          //获取教师id
          String eptid = syseEventsPosted.getEptid();
          if (eptid!=null){
               //查询学校
               Schools schools = queryUsers(eptid);
               //获取学校姓名
               String names = schools.getNames();
               //封装
               syseEventsPosted.setEpschool(names);
          }
          /*结束*/

          //查数据
          List<SyseEventsPosted> stus = competitionMapper.selectByPage(syseEventsPosted);
          for (int i = 0; i < stus.size(); i++) {
               SyseEventsPosted syseEventsPosted1 = stus.get(i);
               String epsigstart = syseEventsPosted1.getEpsigstart();
               String epfinalend = syseEventsPosted1.getEpfinalend();
               String starEnd = epsigstart + "----" + epfinalend;
               syseEventsPosted1.setStarEnd(starEnd);
          }

          //查数目
          long total = competitionMapper.selectCount(syseEventsPosted);

          data.put("stus", stus);
          data.put("total", total);
          return data;

     }

     /**
      * 根据赛事状态进行查询
      */
     @Override
     public List<SyseEventsPosted> selectEpTitle(String epState, String epschool) {
          return competitionMapper.selectEpTitle(epState, epschool);
     }

     /**
      * 修改赛事
      * 后台管理和校园管理平台共同使用
      * @param syseEventsPosted 实体类
      * @return 结果
      */
     @Override
     public int edit(SyseEventsPosted syseEventsPosted) {
          if (StringUtils.isEmpty(syseEventsPosted.getEpsponsor())){
               //主办方id和名称分割
               String[] sponsor = syseEventsPosted.getEpsponsor().split(",");
               //主办方名称
               syseEventsPosted.setEpsponsor(sponsor[0]);
               //封装机构对象，做查询
               SysOrganization org = new SysOrganization();
               org.setOrganizationname(sponsor[0]); //机构名称
               org.setSchoolId(sponsor[1]); //学校ID
               org.setCreate_by(syseEventsPosted.getEptid()); //操作人
               //查询是否有该机构信息，如果没有则添加一个
               List<SysOrganization> orgList = organizationMapper.querySysOrganization(org);
               if (orgList == null || orgList.size() ==0) {
                    organizationMapper.saveSysOrganization(org);
                    //主办方ID
                    syseEventsPosted.setEpsponsorid(org.getOrganizationid());
               } else {
                    //主办方ID
                    syseEventsPosted.setEpsponsorid(orgList.get(0).getOrganizationid());
               }
          }
          //协办方id和名称分割
          /*String eporganizer = syseEventsPosted.getEporganizer();
          if (eporganizer.length()!=0){
               String[] organizer = eporganizer.split(",");
               //封装
               syseEventsPosted.setEporganizer(organizer[0]);
               syseEventsPosted.setEporganizerid(Integer.parseInt(organizer[1]));
          }*/

          //省市区分割
          String eppros = syseEventsPosted.getEppro();
          String[] split=null;
          if (eppros.length() != 0) {
                split= eppros.split("/");
               //判断是否具备省市县三要素
               if (split.length==1){
                    syseEventsPosted.setEppro(split[0]);
               }
               if (split.length == 2) {
                    syseEventsPosted.setEppro(split[0]);
                    syseEventsPosted.setEpcity(split[1]);
               } else if(split.length ==3){
                    syseEventsPosted.setEppro(split[0]);
                    syseEventsPosted.setEpcity(split[1]);
                    syseEventsPosted.setEparea(split[2]);
               }
          }
          //获取文件对象
          MultipartFile fileile = syseEventsPosted.getFile();
          String filepath = "";
          try {
               //如果用户重新上传图片文件
               if (fileile.getSize() != 0) {
                    //删除原有的图片文件
                    Boolean aBoolean = fastDFSUtil.deleteFile(syseEventsPosted.getEppic());
                    if (aBoolean == true || StringUtils.isEmpty(syseEventsPosted.getEppic())) {
                         System.out.println("删除成功");
                         //上传文件
                         filepath = fastDFSUtil.uploadFile(fileile);
                         System.out.println("file：" + filepath);
                         //获取文件全路径
                         String url = fastDFSUtil.getResAccessUrl(filepath);
                         System.out.println("url：" + url);
                         //封装对象
                         syseEventsPosted.setEppic(url);
                    }
               }
          } catch (IOException e) {
               e.printStackTrace();
          }
          //如果赛事状态为“已结束”，那么进度状态也改为已结束
          if ("2".equals(syseEventsPosted.getEpstate())) {
               syseEventsPosted.setProgressStatus("2");
          }
          int edit = competitionMapper.edit(syseEventsPosted);
          return edit;
     }

     /**
      * 删除赛事
      * 后台管理和校园管理平台共同使用
      * @param epid
      * @return 结果
      */
     @Override
     public int remove(int epid) {
          //根据id查对象
          SyseEventsPosted syseEventsPosted = competitionMapper.selectById(epid);
          //获取图片
           String eppic = syseEventsPosted.getEppic();
          int i = 0;
           if (eppic!=null){
                //删除原有图片
                Boolean aBoolean = fastDFSUtil.deleteFile(eppic);
                if (aBoolean == true) {
                     System.out.println("图片删除成功");
                     i = competitionMapper.remove(epid);
                } else {
                     System.out.println("图片删除失败");
                }
           }else {
                i = competitionMapper.remove(epid);
           }
          return i;
     }

     /**
      * 发布
      *后台管理和校园管理平台共同使用
      * @param epid
      * @return 结果
      */
     @Override
     public int editState(int epid) {
          int i = competitionMapper.editState(epid);
          return i;
     }

     /**
      * 通过id查询对象
      *后台管理和校园管理平台共同使用
      * @param epid
      * @return 对象
      */
     @Override
     public SyseEventsPosted selectById(int epid) {
          SyseEventsPosted syseEventsPosted = competitionMapper.selectById(epid);
//          System.out.println("通过id查询："+syseEventsPosted);
          return syseEventsPosted;
     }

     /*
      * 查询标题
      * */
     @Override
     public List<SyseEventsPosted> selectTitle() {
          List<SyseEventsPosted> syseEventsPosteds = competitionMapper.selectTitle();
          return syseEventsPosteds;
     }

     /*
      * 查询主办方
      * */
     @Override
     public List<SyseEventsPosted> selectSponsor() {
          List<SyseEventsPosted> syseEventsPosteds = competitionMapper.selectSponsor();

          return syseEventsPosteds;
     }

     /*
      * 查询赛事状态
      * */
     @Override
     public List<SyseEventsPosted> selectEpstate() {
          List<SyseEventsPosted> syseEventsPosteds = competitionMapper.selectEpstate();

          return syseEventsPosteds;
     }

     /*
      * 查询赛事级别
      * */
     @Override
     public List<SyseEventsPosted> selectEplevel() {
          List<SyseEventsPosted> syseEventsPosteds = competitionMapper.selectEplevel();

          return syseEventsPosteds;
     }

     @Override
     public void updateRankingpath(SyseEventsPosted syseEventsPosted) {
          competitionMapper.updateRankingpath(syseEventsPosted);
     }

     /*
     * 大赛排名分页(全部)
     * */
     @Override
     public List<SyseEventsPosted> rankAllPage(String epLevel) {
          //赛事分页
         List<SyseEventsPosted> eventPostList = competitionMapper.RankAllPage(epLevel);
         for(SyseEventsPosted item : eventPostList) {
              List<Map<String, Object>> workList = competitionMapper.RankAll(item.getEpid());
              item.setWorkList(workList); //添加作品列表
         }
          return eventPostList;
     }

     /*
     *根据赛事id对获奖赛事信息进行拆分
     *把赛事id一样的分为一组
     * */
     public List< List<SyseEventsPosted>> EventsPosteds2(List<SyseEventsPosted> stus){
          //用于接收重复赛事的项目片段数据，返回给方法的调用者
          List< List<SyseEventsPosted>> data = new ArrayList<>();
          //用于临时保存重复赛事的项目片段数据
          Map<Object,List<SyseEventsPosted>> map=new TreeMap<>();
          for (SyseEventsPosted bean:stus){
               //判断当前值是否已经在map中存在
               if (map.containsKey(bean.getEpid())){
                    List<SyseEventsPosted> hasObj=map.get(bean.getEpid());
                    //对象拷贝
                    SyseEventsPosted landTarget=new SyseEventsPosted();
                    BeanUtil.copyProperties(bean,landTarget);
                    hasObj.add(landTarget);
                    new ArrayList<SyseEventsPosted>().add(landTarget);
                    map.put(bean.getEpid(),hasObj);
               }else {
                    List<SyseEventsPosted> newobj=new ArrayList<>();
                    SyseEventsPosted landTarget=new SyseEventsPosted();
                    BeanUtil.copyProperties(bean,landTarget);
                    newobj.add(landTarget);
                    map.put(bean.getEpid(),newobj);
               }
          }
          //取出所有重复的数据，存入到data中
          for (Map.Entry<Object,List<SyseEventsPosted>> entry : map.entrySet()){
               data.add(entry.getValue());
          }
          return data;
     }
     /**查询某个赛事下面的所有赛事状态*/
     @Override
     public List<SyseEventsPosted> selectByEpTitle(Integer epid) {
          //根据id和epstate状态为1查询出赛事信息
          SyseEventsPosted syseEventsPosted = competitionMapper.selectById2(epid);
          if(StringUtils.isNotEmpty(syseEventsPosted.getEptitle())){
               //根据赛事标题获取该赛事下面的所有的赛事阶段
               String eptitle = syseEventsPosted.getEptitle();
               return competitionMapper.selectByEptitle(eptitle);
          }
          return null;
     }

     /**
      * 根据教师id或学生id查询学校信息
      * */
     @Override
     public Schools queryUsers(String id) {
          //根据教师id查询教师信息或根据学生id查询学生信息
          Query query=new Query(Criteria.where("id").is(id));
          Users users = mongoTemplate.findOne(query, Users.class);
          String id2 = String.valueOf(users.getSchool());
          //根据学校id查收学校信息
          Schools schools=studentDao.selectSchoolsById(id2);
          return schools;
     }

     @Override
     public SyseEventsPosted selectSyseEventsPostedById(Integer epid) {
          return competitionMapper.selectById2(epid);
     }

     @Override
     public List<SyseEventsPosted> selectSsTeacherSchool(String epState, String teacherId) {
          if(StringUtils.isNotEmpty(teacherId)){
               Users teacher = studentDao.selectUsersByUserId(teacherId);
               if(!Objects.isNull(teacher)){
                    Schools schools = studentDao.selectSchoolsById(teacher.getSchool());
                    return competitionMapper.selectSsTeacherSchool(epState,schools.getNames());
               }
          }
          return null;
     }

     @Override
     public boolean updateEventsStatus() {
          //查询决赛结束日期和id
          final List<SyseEventsPosted> list = competitionMapper.selectCompetitionAll();
          for (int i=0;i<list.size();i++){
               //获取某一组数据
               SyseEventsPosted sep = list.get(i);
               try {
                    //调用修改
                    if (endDateCompare(sep.getEpfinalend())) {
                         sep.setEpstate("2"); //已结束状态
                         sep.setProgressStatus("2"); //报名状态
//                    } else if(dateCompare(sep.getEpsigstart(), sep.getEpsigend())) {
//                         sep.setProgressStatus("3"); //报名状态
//                    } else if (dateCompare(sep.getEpprestart(), sep.getEppreend())) {
//                         sep.setProgressStatus("4"); //初赛状态
//                    } else if (dateCompare(sep.getEpsecstart(), sep.getEpsecend())) {
//                         sep.setProgressStatus("5"); //复赛状态
//                    } else if (dateCompare(sep.getEpfinalstart(), sep.getEpfinalend())) {
//                         sep.setProgressStatus("6"); //决赛状态
                    }
                    if (!StringUtils.isEmpty(sep.getProgressStatus())) {
                         competitionMapper.updateEpstate(sep);
                    }
               } catch (ParseException e) {
                    e.printStackTrace();
               }
          }
          return false;
     }

     /**
      * 当前日期是否在开始日期与结束日期之内，是返回TRUE，否返回false
      * @param starDate
      * @param endDate
      * @return
      * @throws ParseException
      */
     private boolean dateCompare(String starDate, String endDate) throws ParseException {
          //设置时间格式
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
          if (StringUtils.isEmpty(starDate) || StringUtils.isEmpty(endDate)) {
               return false;
          }
          Date start = sdf.parse(starDate);
          Date end = sdf.parse(endDate);
          //获取系统时间
          Date now = new Date();
          if (start.compareTo(now)<=0 && end.compareTo(now)>=0) {
               return true;
          }
          return false;
     }

     /**
      * 比较赛事时间并做状态变更
      * @param epfinalend 决赛结束时间
      * @throws ParseException
      */
     public boolean endDateCompare(String epfinalend) throws ParseException {
          //设置时间格式
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
          //string转date类型
          Date end = sdf.parse(epfinalend);
          //获取系统时间
          Date now = new Date();
          //拿赛事时间与系统时间做匹对(小于0就调用修改)
          if (end.compareTo(now) < 0) {
               return true;
          }
          return false;
     }
}
